package database;

/**
 * This class reads in a file and displys the puzzle
 * taken from the inputed notes
 * @author jimmy
 *
 */

import java.io.*;
import java.util.*;
import javax.swing.*;
import java.util.Random;

public class LoadFile
{
	PuzzleColor puzCol;
	PuzzlePiece lastTopic;

	ArrayList<PuzzlePiece> pieces;
	public LoadFile()
	{
		puzCol = new PuzzleColor(1f,.5f,0f);
	}
	/**
	 * gets a file from the user and loads a
	 * puzzle from it
	 * @return
	 */
	public PuzzlePiece[] load()
	{
		pieces = new ArrayList();

		JFileChooser chooser = new JFileChooser(".");
	    File file = null;
	    int status = chooser.showOpenDialog(null);
	    if (status == JFileChooser.APPROVE_OPTION)
	    file = chooser.getSelectedFile();
        if(file!=null)//checks for no file
        {
        	try
        	{
        		BufferedReader inputFile = new BufferedReader( new FileReader(file) );
	            String line = inputFile.readLine();
	            while (!(line.compareTo("start")==0))
	            {
	            	line = inputFile.readLine();
	            }
	            line = inputFile.readLine();
	            while (line !=null && !(line.compareTo("stop")==0))
	            {
	            	StringTokenizer st = new StringTokenizer(line, " ");
	            	String temp = st.nextToken();
	            	if(temp.compareTo("new")==0)
	            	{
	            		temp = st.nextToken();
	            		int level = -1;
	            		if(temp.compareTo("topic")==0)//new main topic
	            		{
	            			level = 1;
	            		}
	            		else if(temp.compareTo("subtopic")==0)//new subtopic
	            		{
	            			level = 2;
	            		}
	            		else if(temp.compareTo("microtopic")==0)//new micro topic
	            		{
	            			level = 3;
	            		}
	            		String label = deTokenize(st);
	            		createNewPiece(label, level);
	            	}
	            	else if(temp.compareTo("more")==0)
	            	{
	            		temp = st.nextToken();
	            		if(temp.compareTo("detail")==0)
	            		{
	            			String append = deTokenize(st);
	            			appendLast(append);
	            		}
	            		else
	            		{
	            			System.out.println("invalid input format");
	            		}
	            	}
	            	else if(temp.compareTo("back")==0)//pause and wait for resume
	            	{
	            		System.out.println("back");
	            		temp = st.nextToken();
	            		if(temp.compareTo("to")==0)
	            		{
		            		String puzzleText = deTokenize(st);
		            		line = inputFile.readLine();
		            		st = new StringTokenizer(line," ");
		            		if(st.nextToken().compareTo("append")==0)
		            		{
		            			String append = deTokenize(st);
		            			appendText(puzzleText,append);
		            		}
	            		}
	            	}
	            	else if(temp.compareTo("pause")==0)//pause and wait for resume
	            	{
	            		while (line !=null && !(line.compareTo("resume")==0))
	    	            {
	            			line = inputFile.readLine();
	    	            }
	            	}
	            	line = inputFile.readLine();
				}
	            inputFile.close();
	            randomizeRotate();//randomizes the rotation of the pieces
	            return ((PuzzlePiece[])pieces.toArray(new PuzzlePiece[ pieces.size()]));
        	}
        	catch (FileNotFoundException f)
        	{
        		System.out.println("Error: File Not Found");
        	}
        	catch (IOException e)
        	{
        		System.out.println("Error: Input error");
        	}


        }
        return null;
	}
	/**
	 * appends to the last puzzle that was created
	 * @param append > string to append to the puzzlepiece that was last added
	 */
	private void appendLast(String append)
	{
		PuzzlePiece piece = pieces.get(pieces.size()-1);
		piece.setText(piece.getText()+" "+append);
	}
	/**
	 * appends the puzzle
	 * @param puzzleLabel
	 * @param append
	 */
	private void appendText(String puzzleLabel, String append)
	{
		boolean done =false;
		int index = 0;
		while(!done && index<pieces.size())
		{
			PuzzlePiece piece = pieces.get(index);
			if(piece.getText().compareTo(puzzleLabel)==0)
			{
				piece.setText(piece.getText()+" "+append);
				done = true;
			}
			index++;
		}
	}
	/**
	 * a method to make the rest of a tokenized string
	 * and put it back together into a String
	 * @param st takes a tokenized string
	 * @return a string of the rest of the tokenized strings
	 */
	private String deTokenize(StringTokenizer st)
	{
		String result = "";
		while(st.hasMoreTokens())
		{
			result += st.nextToken()+" ";
		}
		return result;
	}
	/**
	 * creates a new puzzle piece and depending on the level, appends
	 * it to the list of puzzle pieces
	 * @param label
	 * @param level
	 */
	private void createNewPiece(String label, int level)
	{
		Coordinate coord = PuzzleCreator.randomLocation();
		PuzzleCut cut = PuzzleCreator.randomCut();
		pieces.add(new PuzzlePiece(coord,puzCol,label,level));
		if(cut == null)
			System.out.println("cuts null");
		if(pieces.size()!=1)
		{
			if(pieces.get(pieces.size()-1).getLevel()<=2)
			{
				pieces.get(pieces.size()-1).setNeighbor(2,lastTopic,cut);
				lastTopic = pieces.get(pieces.size()-1);
			}
			else
			{
				pieces.get(pieces.size()-1).setNeighbor(0,pieces.get(pieces.size()-2),cut);
			}
		}
		else
		{
			lastTopic = pieces.get(pieces.size()-1);
		}
	}
	/**
	 * randomizes all the pieces rotation
	 *posision
	 */
	private void randomizeRotate()
	{
		for(int i = 0; i < pieces.size();i++)
		{
			Random rand = new Random();
			double lower = (0);
			double upper = (4);
			float r = (int) (rand.nextDouble()*(upper - lower)+lower);
			if(r == 0)
			{
				pieces.get(i).rotateClock();
			}
			else if(r== 1)
			{
				pieces.get(i).rotateClock();
				pieces.get(i).rotateClock();
			}
			else if(r == 2)
			{
				pieces.get(i).rotateCounter();
			}
		}
	}

}
